//
//  releaseDynamicViewController.m
//  AnimationRecommend
//
//  Created by 花花蔡 on 2017/2/23.
//  Copyright © 2017年 ljm. All rights reserved.
//

#import "releaseDynamicViewController.h"
#import "MPTextView.h"
#import "PhotosNavigationController.h"
#import "KYWaterWaveView.h"
#import "ARLoginViewController.h"


@interface releaseDynamicViewController ()<PYPhotosViewDelegate,PhotosNavigationControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate > {
    
    UIImagePickerController *_imagePickerController;
    
    NSMutableArray *_selectedAssets;
    BOOL sender;

}

@property(nonatomic,strong) MPTextView *textView;
@property(nonatomic,strong) PYPhotosView *photosView;
@property(nonatomic,strong) KYWaterWaveView *waterWaveView;



@end

@implementation releaseDynamicViewController {
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [_waterWaveView wave];

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
    [_waterWaveView stop];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initImagePickerController];
    [self setupTextView];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - textView
- (void)setupTextView {
    CGFloat textViewX = PYMargin * 2/AAdaptionWidth();
    _textView = [[MPTextView alloc] initWithFrame:AAdaptionRect(textViewX, 20, kBaseWidth - textViewX * 2, 300)];
    _textView.placeholderText = @"分享你的心情.....";
    _textView.backgroundColor = iCodeTableviewBgColor;
    
    [self.view addSubview:_textView];
    
    CGFloat photoViewY = CGRectGetMaxY(_textView.frame);
    
    _photosView = [PYPhotosView photosView];
    _photosView.py_x = PYMargin * 2;
    _photosView.py_y = PYMargin * 2 + photoViewY;
    _photosView.images = [NSMutableArray new];
    _photosView.delegate = self;
    
    [self.view addSubview:_photosView];
    
    _waterWaveView = [[KYWaterWaveView alloc] initWithFrame:CGRectMake(0, 300, kwidth, kheight - 300)];
    //_waterWaveView.layer.cornerRadius  = _waterWaveView.frame.size.width / 2;
    _waterWaveView.waveSpeed = 6.0f;
    _waterWaveView.waveAmplitude = 6.0f;
    [self.view addSubview:_waterWaveView];

    
}

#pragma mark - delegate
- (void)photosView:(PYPhotosView *)photosView didAddImageClickedWithImages:(NSMutableArray *)images {
    
    __weak typeof(self) weakSelf = self;
    [_textView resignFirstResponder];
    SRActionSheet *sheet = [SRActionSheet sr_actionSheetViewWithTitle:@"选择照片" cancelTitle:@"取消" destructiveTitle:nil otherTitles:@[@"拍照",@"从相册选取"] otherImages:nil selectSheetBlock:^(SRActionSheet *actionSheet, NSInteger index) {
        
        if (index == 0)  [weakSelf openCamera];
        if (index == 1)  [weakSelf openNavigation];
        
    }];
    [sheet show];

}


// 初始化
- (void)setup
{
    self.view.backgroundColor = iCodeTableviewBgColor;
    //[self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backIconTypeTwo"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
   
    UIImage *image = [UIImage imageNamed:@"info_renz"];
    image = [image  imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleDone target:self action:@selector(send)];

    self.title = @"发布分享";
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)send {
    
    
    
    if (sender == NO) {
        __weak typeof(self) weakSelf = self;
        
        if ([[NSUserDefaults standardUserDefaults] boolForKey:isLoginKey]) {
            
            if (([_textView.text isEqualToString:@""] || [_textView.text isEqualToString:@" "] ||[_textView.text isEqualToString:@"  "]) && _photosView.images.count < 1)
                [CLLMessageBarTool showMessageWithType:TWMessageBarMessageTypeError WithTitle:@"发布失败" WithDescription:@"文本不能为空"];
            else {
                [self sendToLeanCloud];
                sender = YES;
            }
        }else {
            [[CLLScottAlertView alloc] showEffAlertViewWithTitle:@"未登录" message:@"是否登录?" WithSureBlock:^(ScottAlertAction *action) {
                [weakSelf presentViewController:[[ARLoginViewController alloc] init] animated:YES completion:nil];
            } WithCancelBlock:^(ScottAlertAction *action) {
                
            } WithVc:self];
        }

    }
    
}

- (void)sendToLeanCloud {
    NSString *text = _textView.text;
    AVUser *user = [AVUser currentUser];
    
    AVObject *product = [AVObject objectWithClassName:@"Product"];
    [product setObject:text forKey:@"text"];
    
    // owner 字段为 Pointer 类型，指向 _User 表
    [product setObject:user forKey:@"owner"];
    for (int i = 0; i < _photosView.images.count; i++) {
        UIImage *image = _photosView.images[i];
        //image = [self OriginImage:image];
        NSData *data = UIImagePNGRepresentation(image);
        AVFile *file = [AVFile fileWithData:data];
        [product setObject:file forKey:[NSString stringWithFormat:@"image_%d",i]];
    }
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.label.text = @"上传中...";
    [product saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
       
        if (succeeded) {
            hud.mode = MBProgressHUDModeText;
            hud.label.text = @"上传成功";
            [hud hideAnimated:YES afterDelay:2.f];
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [CLLMessageBarTool showMessageWithType:TWMessageBarMessageTypeError WithTitle:@"提示" WithDescription:@"上传失败"];
        }
    }];
}

#pragma mark - 缩放图片
//- (UIImage*)OriginImage:(UIImage *)image
//{
//    CGSize size = CGSizeMake(500,700);
//    UIGraphicsBeginImageContext(size);  //size 为CGSize类型，即你所需要的图片尺寸
//    
//    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
//    
//    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
//    
//    UIGraphicsEndImageContext();
//    
//    return scaledImage;   //返回的就是已经改变的图片
//}

#pragma mark - 相册

- (void)initImagePickerController {
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
}

//打开相机
- (void)openCamera {
    //判断是否可以打开照相机
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        //摄像头
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    }
    else
    {
        [[CLLScottAlertView alloc] showOnWindowWithTitle:@"打开失败" WithMessage:@"照相机可能已损坏"];
    }
    
}

//打开相册
//- (void)openPhotoAlbum {
//    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
//    {
//        _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        
//        [self presentViewController:_imagePickerController animated:YES completion:nil];
//    }
//    else
//    {
//        [[CLLScottAlertView alloc] showOnWindowWithTitle:@"打开失败" WithMessage:@"打开相册失败"];
//    }
//}

///拍照完成的回调
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    //图片存入相册
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        //压缩图片
        NSData *data;
        if (UIImagePNGRepresentation(image) == nil)
            data = UIImageJPEGRepresentation(image, 0.1);
        else
            data = UIImagePNGRepresentation(image);
    
        [_photosView.images addObject:[UIImage imageWithData:data]];
        [_photosView reloadDataWithImages:_photosView.images];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

//进入拍摄页面点击取消按钮
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}


/// 图片保存完毕的回调
- (void) image: (UIImage *) image didFinishSavingWithError:(NSError *) error contextInfo: (void *)contextInf{
}


#pragma mark - openNavigation

- (void)openNavigation {
    
    PhotosNavigationController *navigation = [[PhotosNavigationController alloc] initWithMaxImagesCount:9 delegate:self];
    navigation.allowPickingVideo = NO;
    [self presentViewController:navigation animated:YES completion:nil];

}

//用户点击了取消
- (void)PhotosNavigationControllerDidCancel:(PhotosNavigationController *)navigation {
    
}

/// 用户选择好了图片，如果assets非空，则用户选择了原图。
- (void)PhotosNavigationController:(PhotosNavigationController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets {
    
    NSMutableArray *imageArray = [NSMutableArray array];

    if (assets.count != 0) {
        for (int i = 0; i < assets.count; i++) {
            UIImage *temImage = photos[i];
            [_selectedAssets addObject:temImage];
            NSData *data = UIImageJPEGRepresentation(temImage, 1.0);
            [imageArray addObject:[UIImage imageWithData:data]];
        }
    }else {
        for (int i = 0; i < photos.count; i++) {
            UIImage *temImage = photos[i];
            [_selectedAssets addObject:temImage];
            NSData *data = UIImageJPEGRepresentation(temImage, 0.1);
            [imageArray addObject:[UIImage imageWithData:data]];
        }
    }
    
    _photosView.images = imageArray;
    [_photosView reloadDataWithImages:_photosView.images];
}






@end
